#include "Dwarf.Unmanaged.Omp.h"


//Pointers to the factory functions.
static DLLParseArguments pDLLParseArguments;
static DLLUsage pDLLUsage;
static DLLStart pDLLStart;
static DLLStop pDLLStop;

//Pointers to dll.
static HINSTANCE hInstDll;

// Constructor that init strings.
Settings :: Settings()
{
    inputFile = new char[BUFFER_SIZE];
    resultFile = new char[BUFFER_SIZE];
	profileFile = new char[BUFFER_SIZE];

    inputFile[0] = resultFile[0] = profileFile[0] ='\0';
}

// Constructor that dispose strings.
Settings :: ~Settings()
{
    delete inputFile;
    delete resultFile;
	delete profileFile;
}

// Get one line from stream.
static void getNextLine(char* str, FILE* file) 
{
	short count = 0;
	char ch = ' ';    

    while (!feof(file) && (ch == ' ' || ch == '\n' || ch == '\r')) 
    {
        ch = (char)getc(file);
	}

    str[count] = ch;
	while (!feof(file) && ch != '\r' && ch != '\n' && ch != ' ') 
    {
		str[++count] = (ch = (char)getc(file));
	}
	
	str[count] = '\0';
}

// Parse input file into solver's structures.
int Settings::parseConfigFile(Solver* sgsolver) 
{
    FILE *file;

    // Open the file to read from.
    if( fopen_s(&file, inputFile, "rb")) 
    {
        printf("Can't open configfile!\r\n");
        (pDLLUsage)();

        return -1;
    }

    char *str = new char[BUFFER_SIZE];

    //Get epsilon.
    getNextLine(str, file);
    sgsolver->epsilon = atof(str);

    //Get nomber of rows.
    getNextLine(str, file);
    sgsolver->ymax = atoi(str);

    //Get nomber of columns.
    getNextLine(str, file);
    sgsolver->xmax = atoi(str);

    int i,j;

    //Init matrices.
    sgsolver->grid = new double*[sgsolver->ymax];
    sgsolver->tempGrid = new double*[sgsolver->ymax];
    for (j = 0; j < sgsolver->ymax; j ++)
    {
        sgsolver->grid[j] = new double[sgsolver->xmax];
        sgsolver->tempGrid[j] = new double[sgsolver->xmax];
    }

    i = j = 0;

    //Get matrix.
    while(!feof(file) && j < sgsolver->ymax)
    {
        getNextLine(str, file);
        sgsolver->grid[j][i] = atof(str);

        i ++;

        if (i >= sgsolver->xmax) 
        {
            i = 0;
            j ++;
        }
    }    

    delete str;

    //Dispose input file.
    fclose(file);

    return 0;
}

// Init variables, parse cli params and input file.
int Settings::init(int argc, char** argv, Solver *sgsolver) 
{
    
    // Load the dll into the address space
	//fix: C4706
	//if (!(hInstDll = LoadLibraryA("CliTools"))) 
    //{
	hInstDll = LoadLibraryA("CliTools");
	if(!hInstDll)
	{
       printf("Error while loading CliTools.dll.");
        return -1;
    }

    // Retrieve a pointer to the factory function
    pDLLParseArguments = 
        (DLLParseArguments) GetProcAddress(hInstDll, "parseArguments");

    pDLLUsage =
        (DLLUsage) GetProcAddress(hInstDll, "usage");

    pDLLStart = 
        (DLLStart) GetProcAddress(hInstDll, "start");

    pDLLStop = 
        (DLLStop) GetProcAddress(hInstDll, "stop");

    //Parse cli params.
    if ((pDLLParseArguments)(argc, argv, &inputFile, &profileFile,  &resultFile)) 
    {
        FreeLibrary(hInstDll); 
        return -1;
    }

	//Parse input file.
    if (parseConfigFile(sgsolver)) 
    {
        FreeLibrary(hInstDll); 
        return -1;
    }

    //Write settings if it's needed.
    writeSettings(sgsolver);	
    return 0;
}

// Start the time count.
void Settings::start() 
{
    (pDLLStart)();
}

// Problem results output.
void Settings::finish(Solver *sgsolver)
{
    double time;
    (pDLLStop)(&time);

    //Release dll.
    FreeLibrary(hInstDll);//*/

    printf("\r\n");
    printf("Clock time (sec): %.8f \r\n", time);  


    FILE* outputResult = 0;
    FILE* outputProfile = 0;

    if( fopen_s(&outputProfile, profileFile , "wb")) 
    {
        printf("Can't create profile file!\r\n");            
		fclose(outputProfile);
        return;
    }

    if( fopen_s(&outputResult, resultFile , "wb")) 
    {
        printf("Can't create result file!\r\n");   
        fclose(outputResult);
        return;
    }
    

    fprintf(outputProfile, "#Dwarfname:%s\r\n",DWARF_NAME);

    char tmpbuf[BUFFER_SIZE];
    _tzset();
    
    _strdate_s( tmpbuf, BUFFER_SIZE );
    fprintf(outputProfile, "#Time: %s ",tmpbuf);

    _strtime_s( tmpbuf, BUFFER_SIZE );
    fprintf(outputProfile, "%s \r\n",tmpbuf);

    fprintf(outputProfile, "#Dimensions: 2\r\n");
    fprintf(outputProfile, "#Xmax: %i\r\n", sgsolver->xmax);
    fprintf(outputProfile, "#Ymax: %i\r\n", sgsolver->ymax);
    fprintf(outputProfile, "#Result time (sec): %.8f\r\n", time);
	fprintf(outputResult, "#Iterations: %i #Result domain:\r\n", sgsolver->iterations);
    for (int i = 0; i < sgsolver->ymax; i ++) 
    {
        for (int j = 0; j < sgsolver->xmax; j ++) 
        {                
            fprintf(outputResult, "%0.8f ", sgsolver->result[i][j]);
        }
        fprintf(outputResult, "\r\n");
    }
    fprintf(outputProfile, "#eof");

    fclose(outputProfile);
    fclose(outputResult);
	
}

// Write settings.
void Settings::writeSettings(Solver *sgsolver)
{
    // Write general settings.
    printf("Kernel settings summary : \r\n");
	printf("Dwarf name              : %s \r\n", DWARF_NAME);
    printf("Epsilon                 : %0.8f \r\n", sgsolver->epsilon);
    printf("Xmax                    : %d \r\n", sgsolver->xmax);
    printf("Ymax                    : %d \r\n", sgsolver->ymax);
	printf("Input file              : %s \r\n", inputFile);
	printf("Profile file            : %s \r\n", profileFile);    
	printf("Result file             : %s \r\n", resultFile);    
    printf("\r\n"); 
}